import logging
import pymysql
from django.http import JsonResponse, HttpResponse
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from .sqlmap import *
from django.db import connection
from copy import deepcopy
from utils.pageutils import paging_simple
from comment.comservice import add_filter


mysql_tools = MysqlTools(db_config=DB_Config.get("default"))

# 发送的格式
dept_dict = {
    "id": 1,  # 部门id
    "name": "铭泊停车公司",  # 部门名称
    "isChecked": False,  # 写死为False
    "nodeType": 0,  # 人是1,部门是0
    "nowChekced": 0,  # 写死为0
    "children": [],  # 下级部门和该部门的所有人
}

def id_name(params):
    dict = {
        "user_id": "user_id"
            }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    if not params["user_id"]:
        return err_response(210)
    all = {}
    project_id_name = mysql_tools.select_all(UserSqlMap.PROJECT_ID_NANE)        # 项目名称和id
    all["project_id_name"] = project_id_name
    project_status_name = [{"status_id": "1", "status_name": "进场交接"},{"status_id": "2", "status_name": "合同"},{"status_id": "3", "status_name": "招投标"},{"status_id": "4", "status_name": "投资核算"},{"status_id": "5", "status_name": "确定意向"},{"status_id": "6", "status_name": "挂起"}]
    all["project_status"] = project_status_name
    project_status_type = [{"type_id": "1", "type_name": "运营"},{"type_id": "2", "type_name": "设计"},{"type_id": "3", "type_name": "投资"},{"type_id": "4", "type_name": "工程改造"},{"type_id": "5", "type_name": "承包"}]
    all["project_type"] = project_status_type
    dept_id_name = mysql_tools.select_all(UserSqlMap.DEPT_ID_NAME)              # 部门名称id
    all["dept_id_name"] = dept_id_name
    USER_DEPT_ID_NAME = mysql_tools.select_one(UserSqlMap.USER_DEPT_ID_NAME.format(**params))                    ## 部门id名称
    params["dept_id"] = USER_DEPT_ID_NAME.get("dept_id")
    # user_position_id_name = mysql_tools.select_one(UserSqlMap.USER_POSITION_ID_NAME.format(**params))            ## 职位id名称
    # all["user_position_id_name"] = user_position_id_name
    USER_ROLE_ID_NAME = mysql_tools.select_one(UserSqlMap.USER_ROLE_ID_NAME.format(**params))                    ## 权限id名称
    params["role_value"] = USER_ROLE_ID_NAME.get("role_value")
    # if params["role_value"] <= 1:
    #     all["process_reviewed_examine"] = []
    #     all["process_reviewed_create"] = []
    # else:
    #     process_reviewed_create = mysql_tools.select_all(UserSqlMap.PROCESS_REVIEWED_CREATE.format(**params))          # 流程首次审核人
    #     if not process_reviewed_create:
    #         UP_DEPT_ID = mysql_tools.select_one(UserSqlMap.UP_DEPT_ID.format(**params))     # 上级部门
    #         if not UP_DEPT_ID:
    #             all["process_reviewed_create"] = []
    #             ROOT_AND_CEO = mysql_tools.select_all(UserSqlMap.ROOT_AND_CEO)
    #             process_reviewed_examine = ROOT_AND_CEO  # 第二次开始流程审核人
    #             all["process_reviewed_examine"] = process_reviewed_examine
    #         else:
    #             params["dept_id"] = UP_DEPT_ID.get("children_id")           # 本部门没有比自己级别高的就换成上级部门id
    #             process_reviewed_create = mysql_tools.select_all(
    #                 UserSqlMap.PROCESS_REVIEWED_CREATE.format(**params))  # 流程首次审核人
    #             all["process_reviewed_create"] = process_reviewed_create
    #             ROOT_AND_CEO = mysql_tools.select_all(UserSqlMap.ROOT_AND_CEO)
    #             for res in ROOT_AND_CEO:
    #                 if res not in process_reviewed_create:
    #                     process_reviewed_create.append(res)
    #             all["process_reviewed_examine"] = process_reviewed_create
    #     else:
    #         all["process_reviewed_create"] = deepcopy(process_reviewed_create)
    #         ROOT_AND_CEO = mysql_tools.select_all(UserSqlMap.ROOT_AND_CEO)
    #         for res in ROOT_AND_CEO:
    #             if res not in process_reviewed_create:
    #                 process_reviewed_create.append(res)
    #         all["process_reviewed_examine"] = process_reviewed_create

    process_deeply_id_name = mysql_tools.select_all(UserSqlMap.DEEPLY_ID_NAME)                      # 流程紧急程度
    all["process_deeply_id_name"] = process_deeply_id_name
    process_holiday_type_id_name = mysql_tools.select_all(UserSqlMap.holiday_type_id_name)          # 流程请假类型
    all["process_holiday_type_id_name"] = process_holiday_type_id_name
    derate_level = mysql_tools.select_all(UserSqlMap.derate_level)          # 流程减免等级
    all["process_free_stop_derate_level"] = derate_level
    PROCESS_STATUS = mysql_tools.select_all(UserSqlMap.PROCESS_STATUS)          # 流程状态
    all["process_status"] = PROCESS_STATUS
    NOTICE_TYPE = mysql_tools.select_all(UserSqlMap.NOTICE_TYPE)          # 公告类型
    all["notice_type"] = NOTICE_TYPE
    NOTICE_STATUS = mysql_tools.select_all(UserSqlMap.NOTICE_STATUS)          # 公告状态
    all["notice_status"] = NOTICE_STATUS
    NOTE_TYPE = mysql_tools.select_all(UserSqlMap.NOTE_TYPE)          # 日志类型
    all["note_catalog"] = NOTE_TYPE
    PERFORMANCE_STATUS = mysql_tools.select_all(UserSqlMap.PERFORMANCE_STATUS)          # 绩效分类
    all["performance_status"] = PERFORMANCE_STATUS
    TRAIN_STATUS = mysql_tools.select_all(UserSqlMap.TRAIN_STATUS)          # 培训状态
    all["train_status"] = TRAIN_STATUS
    CONFIG_ID = mysql_tools.select_all(UserSqlMap.CONFIG_ID)          # 流程分类
    all["config_id_name"] = CONFIG_ID
    first = mysql_tools.select_one(UserSqlMap.subject1)
    second = mysql_tools.select_all(UserSqlMap.subject2.format(**first))
    last = mysql_tools.select_all(UserSqlMap.subject3)
    for sec in second:
        sec["subordinate_subject"] = []
    for sec in second:
        for las in last:
            if sec["subject_id"] == las["last_subject_id"]:
                # las.pop("last_subject_id")
                sec["subordinate_subject"].append(las)
    first["subordinate_subject"] = second
    all["subject_tree"] = first         # 报销费用的科目树
    TASK_STATUS = mysql_tools.select_all(UserSqlMap.TASK_STATUS)          # 任务状态
    all["task_status"] = TASK_STATUS
    all["priority_level_id_name"] = [{"priority_level": 0, "priority_level_name": "低"},{"priority_level": 1, "priority_level_name": "中"},{"priority_level": 2, "priority_level_name": "高"}]
    # 任务优先级
    # if USER_DEPT_ID_NAME["dept_name"] == "总经办":
    #     TASK_PUSH = mysql_tools.select_all(UserSqlMap.TASK_PUSH_MAX)
    #     TASK_RECIVER = mysql_tools.select_all(UserSqlMap.TASK_RECIVER_MAX.format(**params))
    # else:
        # TASK_PUSH = mysql_tools.select_all(UserSqlMap.TASK_PUSH.format(**params))
        # TASK_RECIVER = mysql_tools.select_all(UserSqlMap.TASK_RECIVER.format(**params))
    # all["task_push"] = TASK_PUSH            # 任务负责人
    # all["task_reciver"] = TASK_RECIVER      # 任务执行人

    # note_receiver = mysql_tools.select_all(UserSqlMap.NOTE_RECEIVER.format(**params))
    note_receiver = mysql_tools.select_all(UserSqlMap.ALL_USER)
    all["task_push"] = note_receiver        # 任务负责人
    all["task_reciver"] = note_receiver        # 任务执行人
    all["note_receiver"] = note_receiver        # 日志抄送人

    note_is_read = {1: "我已读", 0: "我未读"}     # 日志是否已读
    all["note_is_read"] = note_is_read


    plan_status = mysql_tools.select_all(UserSqlMap.PLAN_STATUS)
    all["plan_status"] = plan_status            # 计划状态

    plan_cycle = mysql_tools.select_all(UserSqlMap.PLAN_CYCLE)
    all["plan_cycle"] = plan_cycle            # 计划周期

    plan_type = mysql_tools.select_all(UserSqlMap.PLAN_TYPE)
    all["plan_type"] = plan_type            # 计划类型

    # process_overtime_type = mysql_tools.select_all(UserSqlMap.GET_TYPE_BY_MODEL.format(**{"type_model": "aoa_overtime"}))
    # all["process_overtime_type"] = process_overtime_type

    process_evection_type = mysql_tools.select_all(UserSqlMap.GET_TYPE_BY_MODEL.format(**{"type_model": "aoa_evection"}))
    all["process_evection_type"] = process_evection_type        # 出差流程的交通方式

    process_borrow_type = mysql_tools.select_all(UserSqlMap.GET_TYPE_BY_MODEL.format(**{"type_model": "aoa_borrow"}))
    all["process_borrow_type"] = process_borrow_type        # 借款流程的借款方式


    process_chapter_type = mysql_tools.select_all(UserSqlMap.GET_TYPE_BY_MODEL.format(**{"type_model": "aoa_chapter"}))
    all["process_chapter_type"] = process_chapter_type        # 公章流程的用章类型
    return success_response(all)


def FIND_USER_BY_DEPT(params):
    '''
    根据部门id查人
    '''
    sql_dept = UserSqlMap.dept_people
    if params.get("dept_id") >= 1:
        sql_dept += " where dept_id={dept_id} or dept_id=any(select dept_id from aoa_dept where children_id={dept_id})"
    sql = add_filter(sql_dept, params, ["query_str_name"], **UserSqlMap.FILTER_PARAMS)
    sql_dept_people = sql.format(**params)
    dept_people = mysql_tools.select_all(sql_dept_people)
    if params.get("isall") != 1:
        dept_people = paging_simple(dept_people, params.get("page"), params.get("size"))
    if not dept_people:
        return []
    list = []
    for people in dept_people:
        dept_dict["id"] = people.get("user_id")
        dept_dict["name"] = people.get("real_name")
        dept_dict["nodeType"] = 1
        list.append(deepcopy(dept_dict))
    return list


def copy_people(params):
    '''
    抄送人(全部)
    :param params:
    :return:
    '''
    dict = {
            "user_id": "user_id"
        }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str_name": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    if not params.get("user_id"):
        return err_response(210)

    if params.get("query_str_name"):
        params["dept_id"] = 1
        return success_response(FIND_USER_BY_DEPT(params))
    first = mysql_tools.select_one(UserSqlMap.subject_top)
    if not first:
        return success_response({})
    dept_dict["id"] = first.get("dept_id")
    dept_dict["name"] = first.get("dept_name")
    dept_dict["nodeType"] = 0
    first_dict = deepcopy(dept_dict)
    second = mysql_tools.select_all(UserSqlMap.subject_mid.format(**first))
    second_list = []
    last = mysql_tools.select_all(UserSqlMap.subject_down)
    for sec in second:
        dept_dict["id"] = sec.get("dept_id")
        dept_dict["name"] = sec.get("dept_name")
        dept_dict["nodeType"] = 0
        second_dict = deepcopy(dept_dict)
        for las in last:
            if sec["dept_id"] == las["last_dept_id"]:
                dept_dict["id"] = las.get("dept_id")
                dept_dict["name"] = las.get("dept_name")
                dept_dict["nodeType"] = 0
                las_dict = deepcopy(dept_dict)
                second_dict["children"].append(las_dict)
                params["dept_id"] = las.get("dept_id")
                las_dict["children"].extend(FIND_USER_BY_DEPT(params))
        params["dept_id"] = sec.get("dept_id")
        second_dict["children"].extend(FIND_USER_BY_DEPT(params))
        second_list.append(second_dict)
    params["dept_id"] = 1
    first_dict["children"] = second_list
    first_dict["children"].extend(FIND_USER_BY_DEPT(params))
    return success_response(first_dict)


def copy_process(params):
    '''
    以dict方式返回流程审核人
    :params: copy_people_process的参数
    :return: {dept_id1: [user1, user2]}
    '''
    reviewed_examine = []
    reviewed_create = []
    USER_ROLE_ID_NAME = mysql_tools.select_one(UserSqlMap.USER_ROLE_ID_NAME.format(**params))                    ## 权限id名称
    params["role_value"] = USER_ROLE_ID_NAME.get("role_value")
    params["dept_id"] = USER_ROLE_ID_NAME.get("dept_id")
    if params["role_value"] <= 1:
        reviewed_examine = []
        reviewed_create = []
    else:
        # sql_process_reviewed_create = add_filter(
        #     UserSqlMap.PROCESS_REVIEWED_CREATE, params, ["query_str"], **UserSqlMap.FILTER_PARAMS)          # 流程首次审核人
        sql_process_reviewed_create = UserSqlMap.PROCESS_REVIEWED_CREATE
        sql_process_reviewed_create = sql_process_reviewed_create.format(**params)
        process_reviewed_create = mysql_tools.select_all(sql_process_reviewed_create)          # 流程首次审核人
        if not process_reviewed_create:
            UP_DEPT_ID = mysql_tools.select_one(UserSqlMap.UP_DEPT_ID.format(**params))     # 上级部门
            if not UP_DEPT_ID:
                reviewed_create = []
                # sql_ROOT_AND_CEO = add_filter(UserSqlMap.ROOT_AND_CEO, params, ["query_str"], **UserSqlMap.FILTER_PARAMS)
                sql_ROOT_AND_CEO = UserSqlMap.ROOT_AND_CEO
                sql_ROOT_AND_CEO = sql_ROOT_AND_CEO.format(**params)
                ROOT_AND_CEO = mysql_tools.select_all(sql_ROOT_AND_CEO)
                process_reviewed_examine = ROOT_AND_CEO  # 第二次开始流程审核人
                reviewed_examine = process_reviewed_examine
            else:
                params["dept_id"] = UP_DEPT_ID.get("children_id")           # 本部门没有比自己级别高的就换成上级部门id
                # sql_process_reviewed_create = add_filter(
                #     UserSqlMap.PROCESS_REVIEWED_CREATE, params, ["query_str"], **UserSqlMap.FILTER_PARAMS)
                sql_process_reviewed_create = UserSqlMap.PROCESS_REVIEWED_CREATE
                sql_process_reviewed_create = sql_process_reviewed_create.format(**params)
                process_reviewed_create = mysql_tools.select_all(sql_process_reviewed_create)  # 流程首次审核人
                reviewed_create = deepcopy(process_reviewed_create)
                # sql_ROOT_AND_CEO = add_filter(UserSqlMap.ROOT_AND_CEO, params, ["query_str"], **UserSqlMap.FILTER_PARAMS)
                sql_ROOT_AND_CEO = UserSqlMap.ROOT_AND_CEO
                sql_ROOT_AND_CEO = sql_ROOT_AND_CEO.format(**params)
                ROOT_AND_CEO = mysql_tools.select_all(sql_ROOT_AND_CEO)
                for res in ROOT_AND_CEO:
                    if res not in process_reviewed_create:
                        process_reviewed_create.append(res)
                reviewed_examine = process_reviewed_create
        else:
            reviewed_create = deepcopy(process_reviewed_create)
            # sql_ROOT_AND_CEO = add_filter(UserSqlMap.ROOT_AND_CEO, params, ["query_str"],
            #                               **UserSqlMap.FILTER_PARAMS)
            sql_ROOT_AND_CEO = UserSqlMap.ROOT_AND_CEO
            ROOT_AND_CEO = mysql_tools.select_all(sql_ROOT_AND_CEO.format(**params))
            for res in ROOT_AND_CEO:
                if res not in process_reviewed_create:
                    process_reviewed_create.append(res)
            reviewed_examine = process_reviewed_create

    if params.get("process") == 0:
        list = []
        if reviewed_create:
            for user in reviewed_create:
                dept_dict["id"] = user.get("user_id")
                dept_dict["name"] = user.get("real_name")
                dept_dict["dept_id"] = user.get("dept_id")
                dept_dict["nodeType"] = 1
                list.append(deepcopy(dept_dict))

    elif params.get("process") == 1:
        list = []
        if reviewed_examine:
            for user in reviewed_examine:
                dept_dict["id"] = user.get("user_id")
                dept_dict["name"] = user.get("real_name")
                dept_dict["dept_id"] = user.get("dept_id")
                dept_dict["nodeType"] = 1
                list.append(deepcopy(dept_dict))
    else:
        list = []
    result = {}
    if list:
        for res in list:
            if not result.get(res.get("dept_id")):
                result[res.get("dept_id")] = []
            result[res.get("dept_id")].append(res)
    return result


def page_limit(params, children):
    '''
    对人进行分页
    :children:下属列表
    :params: 传入参数
    '''
    if params.get("isall") != 1:
        list_people = []
        list_dept = []
        for chil in children:
            if chil.get("nodeType") == 1:
                list_people.append(chil)
            else:
                list_dept.append(chil)
        list_people = paging_simple(list_people, params.get("page"), params.get("size"))
        list_people.extend(list_dept)
        return list_people
    else:
        return children



def copy_people_process(params):
    '''
    流程审核人
    :param params:
    :return: 树状图
    '''
    dict = {
        "user_id": "user_id",
        "process": "process"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str_name": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    if not params.get("user_id"):
        return err_response(210)
    people_list = []
    if params.get("query_str_name"):
        for key, val in copy_process(params).items():
            for user in val:
                if params.get("query_str_name") in user.get("name"):
                    if user.get("dept_id"):
                        user.pop("dept_id")
                    people_list.append(user)
        return success_response(people_list)
    first = mysql_tools.select_one(UserSqlMap.subject_top)
    if not first:
        return success_response({})
    dept_dict["id"] = first.get("dept_id")
    dept_dict["name"] = first.get("dept_name")
    dept_dict["nodeType"] = 0
    first_dict = deepcopy(dept_dict)
    second = mysql_tools.select_all(UserSqlMap.subject_mid.format(**first))
    second_list = []
    last = mysql_tools.select_all(UserSqlMap.subject_down)
    for sec in second:
        dept_dict["id"] = sec.get("dept_id")
        dept_dict["name"] = sec.get("dept_name")
        dept_dict["nodeType"] = 0
        second_dict = deepcopy(dept_dict)
        for las in last:
            if sec["dept_id"] == las["last_dept_id"]:
                dept_dict["id"] = las.get("dept_id")
                dept_dict["name"] = las.get("dept_name")
                dept_dict["nodeType"] = 0
                las_dict = deepcopy(dept_dict)
                if las_dict.get("dept_id"):
                    las_dict.pop("dept_id")
                dept_id = las.get("dept_id")
                las.pop("dept_id")
                all_user = copy_process(params).get(dept_id)
                if all_user:
                    for user in all_user:
                        user.pop("dept_id")
                        las_dict["children"].append(user)
                    las_dict["children"] = page_limit(params, las_dict.get("children"))
                second_dict["children"].append(las_dict)
        dept_id = sec.get("dept_id")
        sec.pop("dept_id")
        all_user = copy_process(params).get(dept_id)
        if all_user:
            for user in all_user:
                user.pop("dept_id")
                second_dict["children"].append(user)
        if second_dict.get("children"):
            for i in second_dict.get("children"):
                second_dict["children"].extend(i.get("children"))
        second_dict["children"] = page_limit(params, second_dict.get("children"))
        if second_dict.get("dept_id"):
            second_dict.pop("dept_id")
        second_list.append(second_dict)
    first_dict["children"] = second_list
    if first_dict.get("dept_id"):
        first_dict.pop("dept_id")
    for key ,val in copy_process(params).items():
        for user in val:
            if user not in first_dict.get("children"):
                if user.get("dept_id"):
                    user.pop("dept_id")
                first_dict["children"].append(user)
    first_dict["children"] = page_limit(params, first_dict.get("children"))
    return success_response(first_dict)



@format_response
def index(request):
    return com_views(request, {
        "id_name": id_name,
        "copy_people": copy_people,
        "copy_people_process": copy_people_process
    })
